import { onBeforeMount, onMounted, reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import Rsa from "@/utils/rsa";
import {
  addUserInfo,
  delUserInfo,
  editUserInfo,
  enabledUserInfo,
  getUserInfoList,
  getUserList,
  resetPassword,
} from "../../api/system/userManageApi";
import { checkPhone } from "../../utils";

export default function userManagement() {
  const multipleTable = ref(null);
  const router = useRouter();
  const refForm = ref(null);
  const dialogTitle = ref();
  const resetForm = ref(null);
  //搜索表单
  const searchForm = reactive({});
  //启用禁用状态
  const enabled = ref(false);
  const addForm = reactive({});
  const statusDialogVisible = ref(false);
  //总页数
  const totalNum = ref(Number);
  const pageSize = ref(50);
  const pageNum = ref(1);

  //下拉选择器数据
  const selectOption = ref([
    {
      value: true,
      label: "启用",
    },
    {
      value: false,
      label: "禁用",
    },
  ]);
  //下拉选择器选中值
  const selectValue = ref("全部");
  //全选数组
  const multipleData = ref([]);
  //启用禁用id集合
  const ids = ref([]);
  //移除照片操作
  function handleRemove(file, fileList) {
    fileImgs.value = fileList;
  }
  //图片上传成功时回调
  function handleSuccess(file) {
    addForm.icon = file.data.url;
  }
  //上传文件列表
  const fileImgs = ref([]);
  //打开更改启动禁用对话框
  function status(row) {
    // statusDialogVisible.value = true;
    dialogTitle.value = row.enabled;
    userId.value = row.id;
    enabled.value = row.enabled;
    enabledUserInfo({
      ids: [row.id],
      enabled: !enabled.value,
    }).then(() => {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      getUserData();
    });
  }
  //提交启用禁用
  function submitEnabled() {
    enabledUserInfo(userId.value, {
      enabled: !enabled.value,
      reason: addForm.reason,
    }).then(() => {
      statusDialogVisible.value = false;
      getUserData();
      ElMessage({
        message: "操作成功",
        type: "success",
      });
      addForm.reason = "";
    });
    refForm.value.resetFields();
  }

  //获取图片UrL
  function getImgUrl(url) {
    addForm.icon = url;
  }
  //重置密码
  function resetPas(id) {
    resetPassword(id)
      .then(() => {
        ElMessage({
          message: "密码重置成功",
          type: "success",
        });
      })
      .catch((err) => {
        console.log(err);
      });
  }
  //删除用户操作
  function del(id) {
    ElMessageBox.confirm("您确定要删除这条数据么？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        delUserInfo([id]).then(() => {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          getUserData();
        });
      })
      .catch(() => {
        ElMessage({
          message: "取消操作",
          type: "info",
        });
      });
  }
  //用户ID
  const userId = ref(Number);
  //归属部门
  const departments = ref([]);
  //编辑新增功能
  function edit(row) {
    userId.value = row.id;
    addDialogVisible.value = true;
    if (userId.value) {
      //  获取用户编辑信息
      getUserInfoList(userId.value).then((res) => {
        const userInfo = res.data;
        addForm.username = userInfo.username;
        addForm.mobile = userInfo.mobile;
        addForm.password = Rsa.encrypt(userInfo.password);
        addForm.nickname = userInfo.nickname;
        addForm.enabled = userInfo.enabled;
        addForm.icon = userInfo.icon;
        departments.value = userInfo.departments;
        if (userInfo.icon !== null && userInfo.icon !== "") {
          fileImgs.value.push({ url: userInfo.icon });
        } else {
          fileImgs.value.push({
            url: "https://www.mingxiaobang.cn/upload/admin/admin_user.png",
          });
        }
      });
    }
  }
  const formRef = ref(null);
  //提交
  function submit() {
    //如果用户Id存在发送编辑用户请求
    formRef.value.validate((valid) => {
      if (valid) {
        if (userId.value) {
          editUserInfo(userId.value, {
            enabled: addForm.enabled,
            icon: addForm.icon,
            mobile: addForm.mobile,
            nickname: addForm.nickname,
            password: Rsa.encrypt(addForm.password),
            username: addForm.username,
          }).then(() => {
            ElMessage({
              message: "操作成功",
              type: "success",
            });
            addDialogVisible.value = false;
            search();
            formRef.value.resetFields();
            fileImgs.value = [];
          });
        } else {
          addUserInfo({
            enabled: addForm.enabled,
            icon: addForm.icon,
            mobile: addForm.mobile,
            nickname: addForm.nickname,
            password: Rsa.encrypt(addForm.password),
            username: addForm.username,
          }).then(() => {
            ElMessage({
              message: "添加成功",
              type: "success",
            });
            addDialogVisible.value = false;
            search();
            fileImgs.value = [];
            formRef.value.resetFields();
          });
        }
      }
    });
  }
  // 关闭对话框时的回调
  function handleClose() {
    addDialogVisible.value = false;
    formRef.value.resetFields();
    fileImgs.value = [];
  }
  //取消操作
  function cancel() {
    addDialogVisible.value = false;
    formRef.value.resetFields();
    fileImgs.value = [];
  }
  //重置功能
  function reset() {
    resetForm.value.resetFields();
    getUserData();
  }
  const tableData = ref([]);

  //授权操作
  function authorize(item) {
    router.push({
      name: "UserAuthorize",
      query: {
        userId: item.id,
      },
    });
  }
  //新增编辑对话框显示与隐藏
  const addDialogVisible = ref(false);
  //获取用户分页信息
  function getUserData() {
    getUserList({
      pageNumber: pageNum.value,
      pageSize: pageSize.value,
    }).then((res) => {
      tableData.value = res.data.content;
      //  总页数
      totalNum.value = res.data.totalElements;
    });
  }
  //搜索功能
  function search() {
    getUserList({
      enabled: searchForm.selectValue,
      keyword: searchForm.keyword,
      pageNumber: pageNum.value,
      pageSize: pageSize.value,
    }).then((res) => {
      tableData.value = res.data.content;
    });
  }
  //文件上传数量限制
  function handleOnExceed() {
    ElMessage.warning("只能上传一张图片，请删除图片后重试");
  }
  onBeforeMount(() => {
    getUserData();
  });
  onMounted(() => {
    // getUserData();
  });
  const route = useRoute();
  //监听页面变化，解决返回上一页，数据不刷新问题
  watch(
    () => route.path,
    () => {
      if (route.path === "/system/user-management") {
        getUserData();
      }
    }
  );
  //启用功能
  function start() {
    multipleData.value.map((item) => {
      ids.value.push(item.id);
    });
    enabledUserInfo({
      ids: ids.value,
      enabled: true,
    }).then(() => {
      getUserData();
    });
    getUserData();
  }
  //停用功能
  function stop() {
    multipleData.value.map((item) => {
      ids.value.push(item.id);
    });
    enabledUserInfo({
      ids: ids.value,
      enabled: false,
    }).then(() => {
      getUserData();
    });
  }
  //批量删除
  function selectDel() {
    if (multipleTable.value.length !== undefined) {
      multipleData.value.map((item) => {
        ids.value.push(item.id);
      });
      ElMessageBox.confirm("您确定要批量删除数据吗", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delUserInfo(ids.value).then(() => {
            getUserData();
            ElMessage.success("删除成功");
            ids.value = [];
          });
        })
        .catch(() => {
          ElMessage.info("取消操作");
        });
    } else {
      ElMessage.warning("请先选择数据后再操作");
    }
  }
  //全选功能
  function handleSelectionChange(val) {
    multipleData.value = val;
  }
  //表单验证规则
  const ruleForm = ref({
    mobile: [
      { required: true, message: "请输入手机号" },
      { validator: checkPhone, trigger: "blur" },
    ],
    nickname: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
    username: [{ required: true, message: "请输入账号", trigger: "blur" }],
  });
  return {
    formRef,
    ruleForm,
    getUserData,
    getImgUrl,
    submitEnabled,
    tableData,
    resetForm,
    resetPas,
    submit,
    search,
    selectOption,
    status,
    totalNum,
    pageSize,
    pageNum,
    refForm,
    dialogTitle,
    selectValue,
    start,
    selectDel,
    handleSelectionChange,
    statusDialogVisible,
    addForm,
    userId,
    edit,
    reset,
    stop,
    multipleTable,
    searchForm,
    cancel,
    del,
    authorize,
    addDialogVisible,
    handleRemove,
    handleSuccess,
    fileImgs,
    departments,
    handleOnExceed,
    handleClose,
  };
}
